package com.cinematicketscaning.app.controller

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.WindowManager
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.cinematicketscaning.app.R
import com.cinematicketscaning.app.controller.base.BaseActivity
import com.cinematicketscaning.app.viewmodel.LoginVM
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseActivity() {
    private lateinit var viewModel:LoginVM
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(R.layout.activity_login)
        initViewModel()
        initView()
    }

    private fun initViewModel() {
        viewModel = ViewModelProviders.of(this).get(LoginVM::class.java)
        viewModel.isRememberAccount.observe(this, Observer {
            img_remember_pwd.setImageResource(if (it) R.mipmap.bosera_icon_checkbox_default else R.mipmap.bosera_icon_login_checkbox_unselected)
        })
        viewModel.isRememberAccount.value = false
    }

    private fun initView() {
        checkInput()
        val watcher = object: TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                checkInput()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        }
        edit_account.addTextChangedListener(watcher)
        edit_pwd.addTextChangedListener(watcher)
        img_remember_pwd.setOnClickListener {
            viewModel.isRememberAccount.value = !viewModel.isRememberAccount.value!!
        }
        btn_login.setOnClickListener {
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }
    }

    private fun checkInput() {
        btn_login.isEnabled =
                !edit_account.text.toString().isNullOrEmpty() &&
                !edit_pwd.text.toString().isNullOrEmpty()
    }
}
